//
//  AddToPlayListStep1ViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/11.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

private let audioCellIdentifier = "AudioTableCell"
private let headerIdentifier = "AddToPlayListSectionHeader"

class AddToPlayListStep1ViewController: BaseViewController {
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var tableView: UITableView!
  @IBOutlet private weak var checkedCountLabel: UILabel!
  @IBOutlet private weak var allButton: UIButton!
  @IBOutlet private weak var nextButton: UIButton!
  
  // MARK: - Private vars
  
  private var selectedIndexPathes = [IndexPath]()
  
  // MARK: - Private methods
  
  private func prepareUI() {
    tableView.register(UINib(nibName: audioCellIdentifier, bundle: nil), forCellReuseIdentifier: audioCellIdentifier)
    tableView.register(UINib(nibName: headerIdentifier, bundle: nil), forHeaderFooterViewReuseIdentifier: headerIdentifier)
    
    tableView.contentInset = UIEdgeInsets.init(top: 20, left: 0, bottom: 10, right: 0)
    tableView.scrollIndicatorInsets = tableView.contentInset
    
    reSetUIForCheckedCount()
  }
  
  private func reSetUIForCheckedCount() {
    if selectedIndexPathes.count > 0 {
      checkedCountLabel.text = "共选择\(selectedIndexPathes.count)个声音"
      nextButton.isEnabled = true
    } else {
      checkedCountLabel.text = "没有选择声音"
      nextButton.isEnabled = false
    }
    if selectedIndexPathes.count == audios!.count {
      allButton.setTitle("全部取消", for: .normal)
    } else {
      allButton.setTitle("全部选择", for: .normal)
    }
  }
  
  private func set(_ indexPath: IndexPath, checked: Bool) {
    if checked {
      // add indexPath
      if !selectedIndexPathes.contains(indexPath) {
        selectedIndexPathes.append(indexPath)
      }
    } else {
      // remove indexPath
      if let index = selectedIndexPathes.index(of: indexPath) {
        selectedIndexPathes.remove(at: index)
      }
    }
    selectedIndexPathes = selectedIndexPathes.sorted { $0.row < $1.row }
    reSetUIForCheckedCount()
  }
  
  // MARK: - Public vars
  
  var audios: [Audio]?
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    prepareUI()
  }
  
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ShowAddPlaylistStep2Segue" {
      var selectedAudios = [Audio]()
      selectedIndexPathes.forEach {
        if let audio = audios?[$0.row] {
          selectedAudios.append(audio)
        }
      }
      
      let step2ViewController = segue.destination as! AddToPlayListStep2ViewController
      step2ViewController.selectedAudios = selectedAudios
    }
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  // MARK: - IBActions
  
  @IBAction func checkOrUnCheckAll() {
    if selectedIndexPathes.count < audios!.count {
      // check all
      selectedIndexPathes = [IndexPath]()
      for i in 0 ..< audios!.count {
        selectedIndexPathes.append(IndexPath(row: i, section: 0))
      }
      tableView.visibleCells.forEach {
        ($0 as! AudioTableCell).isChecked = true
      }
    } else {
      // uncheck all
      selectedIndexPathes = [IndexPath]()
      tableView.visibleCells.forEach {
        ($0 as! AudioTableCell).isChecked = false
      }
    }
    reSetUIForCheckedCount()
  }
  
  @IBAction func dismiss(_ sender: UIBarButtonItem) {
    let nav = navigationController as! BaseNavigationController
    nav.dismissDelegate?.dismiss(navigationController: nav, completion: nil)
  }
  
  // MARK: - Public methods
  
  
}

extension AddToPlayListStep1ViewController: UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    return 1
  }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return audios?.count ?? 0
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: audioCellIdentifier, for: indexPath) as! AudioTableCell
    if let audio = audios?[indexPath.row] {
      cell.prepare(audio: audio, mode: .selectable)
      cell.isChecked = selectedIndexPathes.contains(indexPath)
    }
    return cell
  }
  
  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier) as! AddToPlayListSectionHeader
    let backgroundView = UIView(frame: header.bounds)
    backgroundView.backgroundColor = .clear
    header.backgroundView = backgroundView
    header.headerLabel.text = "请选择声音"
    return header
  }
}

extension AddToPlayListStep1ViewController: UITableViewDelegate {
  
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! AudioTableCell
    cell.isChecked = !cell.isChecked
    set(indexPath, checked: cell.isChecked)
    tableView.deselectRow(at: indexPath, animated: true)
  }
  
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 60
  }
  
  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return AddToPlayListSectionHeader.defaultHeight
  }
}
